<template>
  <div class="app-container">
    <div v-show="sale.deskId !== ''">
      <!-- 步骤条 -->
      <div>
        <el-steps :space="1000" :active="1" align-center>
          <el-step title="点 菜"></el-step>
          <el-step title="结 账"></el-step>
        </el-steps>
      </div>
      <el-card style="margin-left: 60px;margin-right:60px;" :body-style="cardStyle">
        <!-- 添加菜品 -->
        <div class="filter-container">
          <el-form>
            <el-form-item>
              <span style="fontSize: 20px;padding-right:20px;">{{this.sale.uuid}}</span>
              <!-- <span><el-button type="danger" @click="dropSale">作 废</el-button></span> -->
            </el-form-item>
          </el-form>
          <el-dialog :visible.sync="addShow" center width="450px">
            <el-form style='width: 300px; margin-left:50px;' label-position="left" label-width="70px">
              <el-form-item label="菜品名">
                <el-select v-model="curSaleLineItem.dishes"
                        filterable
                        remote
                        reserve-keyword
                        :remote-method="transformDishesList"
                        :loading="loading">
                  <el-option 
                      v-for="item in dishesListOption"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="数量">
                <el-input-number :min="1" v-model="curSaleLineItem.amount"></el-input-number>
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="curSaleLineItem.remark"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button type="danger" @click="addItem">添 加</el-button>
            </div>
          </el-dialog>
        </div>

        <!-- 菜品列表 -->
        <el-table :data="sale.saleLineItems" v-loading.body="listLoading" element-loading-text="拼命加载中"
                  highlight-current-row fit>
          <el-table-column align="center" label="菜品名称" width="460">
            <template slot-scope="scope">
              <img :src="scope.row.dishes.avatar" style="height: 50px;width: 50px"/>
              <span style="font-size: 18px;padding-left: 200px;">{{scope.row.dishes.dishesName}}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="dishes.price" label="菜品单价" width="160" :formatter="priceFormatter"></el-table-column>
          <el-table-column align="center" label="数量" width="200">
            <template slot-scope="scope">
              <el-input-number v-model="scope.row.amount" @change="handleChange(scope.$index)" :min="1"></el-input-number>
            </template>
          </el-table-column>
          <el-table-column align="center" prop="remark" label="备注" width="260"></el-table-column>
          <el-table-column align="center" prop="subTotal" label="小计" width="160" :formatter="subTotalFormatter"></el-table-column>
          <el-table-column align="center" label="管理" width="200px" v-if="hasPerm('dishes:edit')">
            <template slot-scope="scope">
              <el-button type="danger" icon="el-icon-delete" @click="removeItem(scope.$index)" size="small">删 除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row :gutter="20">
          <el-col :span="20"><div style="fontSize: 20px;">总计: {{this.sale.total}}</div></el-col>
          <el-col :span="4">
            <el-button type="danger" @click="makeSale">结 账</el-button>
            <el-button type="danger" @click="showAdd()">点 菜
              </el-button>
          </el-col>
        </el-row>
      </el-card>

      <!-- 支付页面 -->
      <el-dialog :visible.sync="paymentShow" title="支付" center width="450px">
        <el-form style='width: 300px; margin-left:50px;' label-position="left" label-width="100px">
          <!-- <el-form-item label="订单编号">
            <el-input readonly v-model="payment.saleId"></el-input>
          </el-form-item> -->
          <el-form-item label="应付金额">
            <el-input readonly v-model="payment.shouldPay"></el-input>
          </el-form-item>
          <el-form-item label="选择支付方式">
            <el-select v-model="payment.payWay">
              <el-option
                v-for="item in payWay"
                :key="item.value"
                :label="item.label"
                :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="实付金额" v-if="payment.payWay === '1'">
            <el-input type="number" v-model="payment.realPay" @input="inputRealPay"></el-input>
          </el-form-item>
          <el-form-item label="找零" v-if="payment.payWay === '1'">
            <el-input type="number" v-model="payment.change" readonly></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button type="danger" @click="paymentConfirm" v-if="payment.payWay === '1'">确认支付</el-button>
            <el-button type="danger" @click="waitScan" v-if="payment.payWay === '0'">扫描付款码</el-button>
          </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import math from 'mathjs'
export default {
    data() {
      return {
        sale: {
          deskId: '',
          uuid: '',
          saleLineItems: [],
          total: 0.0
        },
        curSaleLineItem: {
          dishes: {},
          amount: 0,
          subTotal: 0.0,
          remark: ''
        },
        dishesList: [],
        dishesListOption: [],
        state: [],
        loading: false,
        paymentShow: false,
        listLoading: false,
        cardStyle: {
          paddingLeft: '100px'
        },
        addShow: false,
        payment: {
          saleId: 201905022200530002,
          payWay: '',
          shouldPay: 0.0,
          realPay: 0.0,
          change: 0.0
        },
        payWay: [
          {
            label: '在线支付',
            value: '0'
          },
          {
            label: '现金支付',
            value: '1'
          }
        ]
      }
    },
    created() {
      const deskId = this.$route.params.id
      if (deskId) {
        this.getSale(deskId)
      }
    },
    mounted() {
      this.getDishesList()
    },
    methods: {
      inputRealPay() {
        if (this.payment.shouldPay && this.payment.realPay) {
          if (this.payment.shouldPay <= this.payment.realPay) {
            this.payment.change = math.round(math.subtract(this.payment.realPay, this.payment.shouldPay), 1)
            
          } else {
            this.payment.change = ''
          }
        }
      },
      // get Sale
      async getSale(deskId) {
        const res = await this.$api.pos.getSale(deskId)
        this.sale = res.data
        console.log(this.sale)
      },
      // add SaleLineItem
      async addItem() {
        const res = await this.$api.pos.addSaleLineItem(this.sale.deskId, this.curSaleLineItem)
        this.curSaleLineItem = {
          //dishes: {},
          amount: 0,
          subTotal: 0.0
        }
        this.addShow = false
        this.sale = res.data
      },
      // remove SaleLineItem
      removeItem(index) {
        let _vue = this;
        this.$confirm('确认删除?', '提示', {
          confirmButtonText: '确认',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          const item = _vue.sale.saleLineItems[index]
          const res = await this.$api.pos.removeSaleLineItem(_vue.sale.deskId, item)
          _vue.sale = res.data;
          _vue.$notify.success('删除成功')
        })
      },
      // drop Sale
      dropSale() {
        let _vue = this;
        this.$confirm('确认放弃?', '提示', {
          confirmButtonText: '确认',
          showCancelButton: false,
          type: 'warning'
        }).then(async () => {
          await _vue.$api.pos.dropSale(_vue.sale.deskId)
          _vue.sale = {
            deskId: '',
            uuid: '',
            saleLineItems: [],
            total: 0.0
          }
          _vue.$message.success('删除成功')
        })
      },
      // make Sale
      async makeSale() {
        if (this.sale.saleLineItems.length === 0) {
          return;
        }
        this.payment.shouldPay = this.sale.total
        this.payment.saleId
        this.paymentShow = true
      },
      async getDishesList() {
        const res = await this.$api.dishes.list('1','1',false)
        this.state = res.data
        this.dishesList = this.state.map(item => {
            return { value: item, label: item.dishesName }
        })
      },
      transformDishesList(query) {
        if (query !== '') {
          this.loading = true;
          setTimeout(() => {
              this.loading = false;
              this.dishesListOption = this.dishesList.filter(item => {
                  return item.label.toLowerCase()
                    .indexOf(query.toLowerCase()) > -1;
              });
          }, 200);
        } else {
          this.dishesListOption = [];
        }
      },
      waitScan() {
        const loading = this.$loading({
          lock: true,
          text: '等待付款中...',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        this.payment.realPay = this.payment.shouldPay
        this.payment.change = 0.0
        setTimeout(async () => {
          const res1 = await this.$api.pos.makeSale(this.sale.deskId)
          this.payment.saleId = res1.data.id
          const res2 = await this.$api.payment.makePayment(this.payment)
          this.sale = {
            deskId: '',
            uuid: '',
            saleLineItems: [],
            total: 0.0
          }
          loading.close()
          this.$notify.success('支付成功')
          this.paymentShow = false
          // this.dishesList = []
          this.$router.push('/desk')
        }, 2000);
      },
      async paymentCancel() {
        this.paymentShow = false
      },
      async paymentConfirm() {
        const res1 = await this.$api.pos.makeSale(this.sale.deskId)
        this.payment.saleId = res1.data.id
        const res2 = await this.$api.payment.makePayment(this.payment)
        this.sale = {
          deskId: '',
          uuid: '',
          saleLineItems: [],
          total: 0.0
        }
        this.paymentShow = false
        this.$router.push('/desk')
      },
      priceFormatter(row, column) {
        return '￥ ' + row.dishes.price
      },
      subTotalFormatter(row, column) {
        return '￥ ' + row.subTotal
      },
      handleChange(index) {
        this.curSaleLineItem = this.sale.saleLineItems[index]
        this.addItem()
      },
      showAdd() {
        this.addShow = true
      }
    }
}
</script>

<style>
  .pay-footer {
    position: fixed;
    bottom: 0px;
    width: 100%;
  }
  .order-info {
    padding-right: 20px;
  }
</style>
